package com.zwk.edu.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zwk.edu.entity.Subject;
import com.zwk.edu.entity.excel.SubjectData;
import com.zwk.edu.entity.subject.OneSubject;
import com.zwk.edu.entity.subject.TwoSubject;
import com.zwk.edu.listener.SubjectExcelListener;
import com.zwk.edu.mapper.SubjectMapper;
import com.zwk.edu.service.SubjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author zwk
 * @since 2022-08-21
 */
@Service
public class SubjectServiceImpl extends ServiceImpl<SubjectMapper, Subject> implements SubjectService {

    @Autowired
    private SubjectMapper subjectMapper;

    // 添加课程分类
    @Override
    public void saveByExcel(MultipartFile multipartFile, SubjectService subjectService) {

        try {
            InputStream is = multipartFile.getInputStream();
            EasyExcel.read(is, SubjectData.class, new SubjectExcelListener(subjectService)).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @Override
    public List<OneSubject> findAllSubject() {

        // 查询所有一级分类
        QueryWrapper<Subject> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("parent_id", "0");
        List<Subject> oneSubjects = subjectMapper.selectList(wrapper1);

        // 查询所有二级分类
        QueryWrapper<Subject> wrapper2 = new QueryWrapper<>();
        wrapper2.ne("parent_id", "0");
        List<Subject> twoSubjects = subjectMapper.selectList(wrapper2);

        List<OneSubject> list = new ArrayList<>();

        // 封装一级分类
        for (Subject subject1: oneSubjects
             ) {
            OneSubject oneSubject = new OneSubject();
            // 将subject的数据复制给oneSubject
            BeanUtils.copyProperties(subject1, oneSubject);

//            list.add(oneSubject);

            // 封装二级分类
            List<TwoSubject> childrenList = new ArrayList<>();
            for (Subject subject2: twoSubjects
                 ) {
                TwoSubject twoSubject = new TwoSubject();
                // 如果subject2是subject1的孩子
                if (subject2.getParentId().equals(subject1.getId())){
                    BeanUtils.copyProperties(subject2, twoSubject);
                    childrenList.add(twoSubject);
                }
            }
            oneSubject.setChildren(childrenList);

            // 放到上面（72行）也没有错, list中的元素引用堆中的对象, 对象属性改变时, list中的元素也发生改变
            list.add(oneSubject);
        }

        return list;
    }
}
